package com.melody.android.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.melody.android.R
import com.melody.android.logic.model.Song
import com.melody.android.logic.util.MediaPlayer
import com.melody.android.logic.util.storageSelectedSong
import com.melody.android.ui.viewModel.SongViewModel

class SongAdapter(private val songViewModel: SongViewModel, private val songList: List<Song>) : RecyclerView.Adapter<SongAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val songCover: ImageView = view.findViewById(R.id.img_song_cover)
        val songName: TextView = view.findViewById(R.id.txt_song_name)
        val songAuthor: TextView = view.findViewById(R.id.txt_song_author)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_song, parent, false)
        val viewHolder = ViewHolder(view)
        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.adapterPosition
            val song = songList[position]

            songViewModel.selectSong(song)
            // 播放歌曲
            MediaPlayer.playSong(song.name)
            // 存储当前选中的歌曲
            storageSelectedSong(parent.context, song)
        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val song = songList[position]
        holder.songCover.setImageResource(song.cover)   // 歌曲封面
        holder.songName.text = song.name                // 歌曲名称
        holder.songAuthor.text = song.author            // 歌曲作者
    }

    override fun getItemCount() = songList.size

}